import { useEffect, useRef, useState } from "react";
import {
  Button,
  Card,
  Col,
  Drawer,
  Dropdown,
  Form,
  Input,
  Row,
  Select,
  Space,
  Spin,
  Tabs,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import routingService, {
  type PageListReq,
} from "@/api/services/mes/routingService";
import type { MesRouting } from "./entity";
import { toast } from "sonner";
import { t } from "@/locales/i18n";
import TableDictTag from "@/components/grid/TableDictTag";
import MesRoutingProcessPage, {
  type MesRoutingProcessHandles,
} from "./process";
import MesRoutingProductPage, {
  type MesRoutingProductHandles,
} from "./material";
import CustomTable from "@/components/grid/CustomTable";
import useDictionary from "@/hooks/system/useDictionary";

const { TextArea } = Input;

export default function MesRoutingPage() {
  const processRef = useRef<MesRoutingProcessHandles>(null);
  const productRef = useRef<MesRoutingProductHandles>(null);

  const [loading, setLoading] = useState(false);
  const [submitLoading, setSubmitLoading] = useState(false);
  const [queryParams, setQueryParams] = useState<PageListReq>({
    code: undefined,
    name: undefined,
    status: undefined,
    page: 1,
    pageSize: 10,
  });
  const [total, setTotal] = useState(0);
  const [list, setList] = useState<MesRouting[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [editingData, setEditingData] = useState<MesRouting | null>(null);
  const [form] = Form.useForm();
  const [isView, setIsView] = useState(true);

  //动态设置表格高度
  const [tableScrollY, setTableScrollY] = useState(0);
  const PAGE_OFFSET_HEIGHT = 405;
  const updateTableHeight = () => {
    const newHeight = window.innerHeight - PAGE_OFFSET_HEIGHT;
    setTableScrollY(newHeight > 200 ? newHeight : 200); // 保证最小高度
  };

  useEffect(() => {
    updateTableHeight(); // 初始化
    window.addEventListener("resize", updateTableHeight);
    return () => window.removeEventListener("resize", updateTableHeight);
  }, []);

  const processRoutingStatus = useDictionary("process_routing_status");

  const columns: ColumnsType<MesRouting> = [
    {
      title: "工艺路线编号",
      width: 120,
      key: "code",
      dataIndex: "code",
    },
    {
      title: "工艺路线名称",
      width: 120,
      key: "name",
      dataIndex: "name",
    },
    {
      title: "状态",
      width: 120,
      key: "status",
      dataIndex: "status",
      render: (_, record) => (
        <TableDictTag
          dictCode="process_routing_status"
          value={record.status ?? ""}
        />
      ),
    },
    {
      title: "工艺路线说明",
      width: 120,
      key: "remark",
      dataIndex: "remark",
    },
    {
      title: "操作",
      fixed: "right",
      key: "operation",
      align: "center",
      width: 100,
      render: (_, record) => (
        <Space>
          <Button type="link" onClick={() => handleView(record)}>
            {t("common.view")}
          </Button>
          <Button type="link" onClick={() => handleEdit(record)}>
            {t("common.edit")}
          </Button>
        </Space>
      ),
    },
  ];

  //加载表格数据
  const fetchPageList = () => {
    setLoading(true);
    routingService
      .pageList(queryParams)
      .then((res) => {
        setList(res.records);
        setTotal(res.total);
      })
      .catch((error) => {
        console.log(error);
        toast.error("获取数据失败！", error);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
  useEffect(() => {
    fetchPageList();
  }, [queryParams]);

  //选择其他页
  const handlePageChange = (newPage: number, newPageSize: number) => {
    setQueryParams((prev) => ({
      ...prev,
      page: newPage,
      pageSize: newPageSize,
    }));
  };

  //触发编辑按钮
  const handleEdit = (mesRouting: MesRouting) => {
    setEditingData(mesRouting);
    form.setFieldsValue(mesRouting);
    setDrawerVisible(true);
    setIsView(false);
  };

  //触发视图按钮
  const handleView = (mesRouting: MesRouting) => {
    setEditingData(mesRouting);
    form.setFieldsValue(mesRouting);
    setIsView(true);
    setDrawerVisible(true);
  };

  //提交表单数据
  const handleSubmit = async (values: MesRouting) => {
    try {
      setSubmitLoading(true);

      //工艺组成
      const deleteProcessIds = processRef.current?.getDeleteIds();
      const addProcess = processRef.current?.getAddList();
      const updateProcess = processRef.current?.getUpdateList();

      //工艺路线关联产品
      const deleteProductIds = productRef.current?.getDeleteIds();
      const addProducts = productRef.current?.getAddList();
      const updateProducts = productRef.current?.getUpdateList();

      const data = {
        ...values,
        id: editingData?.id,
        deleteProcessIds: deleteProcessIds,
        addProcess: addProcess,
        updateProcess: updateProcess,
        deleteProductIds: deleteProductIds,
        addProducts: addProducts,
        updateProducts: updateProducts,
      };
      if (editingData) {
        await routingService.update(data);
        toast.success("更新工艺路线成功");
      } else {
        await routingService.add(data);
        toast.success("创建工艺路线成功");
      }
      setDrawerVisible(false);
      setEditingData(null);
      form.resetFields();
      fetchPageList();
    } catch (error) {
      toast.error(`保存失败: ${error.message}`);
    } finally {
      setSubmitLoading(false);
    }
  };

  const handleDrawerClose = () => {
    setDrawerVisible(false);
    setEditingData(null);
    form.resetFields();
  };

  const handleAdd = () => {
    setEditingData(null);
    form.resetFields();
    setDrawerVisible(true);
    setIsView(false);
  };

  const handleDelete = async () => {
    try {
      setLoading(true);
      await routingService.remove(selectedRowKeys);
      toast.success("删除工艺路线成功");
      setSelectedRowKeys([]);
      fetchPageList();
    } catch (error) {
      toast.error(`删除失败: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  //更新状态
  const updateStatus = async (status: string) => {
    if (selectedRowKeys.length === 0) {
      toast.error("请先选择要操作的工艺路线");
      return;
    }

    const selectedRows = list.filter(item => selectedRowKeys.includes(item.id));
    const allSameStatus = selectedRows.every(row => row.status === selectedRows[0]?.status);
    if (!allSameStatus) {
      toast.error("请选择状态一致的工艺路线进行操作");
      return;
    }

    if (status === "released") {
      // 只有所有选中行的status为draft时才能发布
      const allDraft = selectedRows.every(row => row.status === "draft");
      if (!allDraft) {
        toast.error("只有草稿状态的工艺路线才能发布");
        return;
      }
    }
    if (status === "draft") {
      // 只有所有选中行的status为released时才能取消发布
      const allDraft = selectedRows.every(row => row.status === "released");
      if (!allDraft) {
        toast.error("只有发布状态的工艺路线才能取消发布");
        return;
      }
    }

    try {
      setLoading(true);
      await routingService.updateStatus(selectedRowKeys, status);
      if (status === "released") {
        toast.success("发布成功");
      } else if (status === "draft") {
        toast.success("取消发布成功");
      } else if (status === "obsolete") {
        toast.success("作废成功");
      } else {
        toast.success("工艺路线状态更新成功");
      }
      setSelectedRowKeys([]);
      fetchPageList();
    } catch (error) {
      toast.error(`更新状态失败: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Spin spinning={submitLoading} tip="数据提交中..." size="large">
      <Card className="mb-4">
        <Form
          layout="inline"
          onFinish={(values) => {
            setQueryParams((prev) => ({
              ...prev,
              ...values,
              page: 1,
            }));
          }}
        >
          <Form.Item name="code" label="工艺路线编号">
            <Input placeholder="请输入工艺路线编号" allowClear />
          </Form.Item>
          <Form.Item name="name" label="工艺路线名称">
            <Input placeholder="请输入工艺路线名称" allowClear />
          </Form.Item>
          <Form.Item name="status" label="状态">
            <Select options={processRoutingStatus} placeholder="请输入状态" allowClear style={{ width: 170 }} />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button
              className="ml-2"
              onClick={() => {
                setQueryParams({ page: 1, pageSize: 10 });
              }}
            >
              重置
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <div className="h-4" />
      <Card>
        <CustomTable
          loading={loading}
          columnsConfig={columns}
          dataSource={list}
          total={total}
          selectedRowKeys={selectedRowKeys}
          setSelectedRowKeys={setSelectedRowKeys}
          current={queryParams.page}
          pageSize={queryParams.pageSize}
          onRefresh={fetchPageList}
          onPageChange={handlePageChange}
          selectable
          toolbarButtons={
            <>
              <Button type="primary" onClick={handleAdd}>
                新增
              </Button>
              <Button
                danger
                disabled={selectedRowKeys.length === 0}
                onClick={handleDelete}
              >
                删除
              </Button>
              <Button.Group>
							<Button 
                type="primary" 
                disabled={selectedRowKeys.length === 0}
                onClick={() => updateStatus("released")}>
								发布
							</Button>
							<Button
								type="primary"
                disabled={selectedRowKeys.length === 0}
                onClick={(e) => {
                  e.stopPropagation();
                }}
								style={{ padding: 0, border: "none",  boxShadow: "none" }}
							>
							<Dropdown
									menu={{
										items: [
											{
												key: "unpublish",
												label: "取消发布",
												onClick: () => updateStatus("draft"),
											},
											{
												key: "void",
												label: "作废",
												onClick: () => updateStatus("obsolete"),
											},
										],
									}}
									placement="bottomLeft"
									trigger={["click"]}
								>
									<span style={{ padding: "0 8px", cursor: "pointer" }}>▼</span>
								</Dropdown>
							</Button>
						</Button.Group>
            </>
          }
          scroll={{ y: tableScrollY }}
        />
      </Card>
      <Drawer
        title={editingData ? "编辑工艺路线" : "新增工艺路线"}
        width={880}
        open={drawerVisible}
        onClose={handleDrawerClose}
        footer={
          <div className="flex justify-end gap-2">
            <Button onClick={handleDrawerClose}>取消</Button>
            {!isView && (
              <Button type="primary" onClick={() => form.submit()}>
                确定
              </Button>
            )}
          </div>
        }
      >
        <Form
          form={form}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
          onFinish={handleSubmit}
          disabled={isView}
        >
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="code"
                label="编号"
                rules={[
                  {
                    required: true,
                    message: "请填写工艺路线编号",
                  },
                ]}
              >
                <Input placeholder="请输入工艺路线编号" allowClear />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="name"
                label="名称"
                rules={[
                  {
                    required: true,
                    message: "请填写工艺路线名称",
                  },
                ]}
              >
                <Input placeholder="请输入工艺路线名称" allowClear />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="remark"
            label="说明"
            labelCol={{ span: 3 }}
            wrapperCol={{ span: 21 }}
          >
            <TextArea />
          </Form.Item>

          <Tabs
            defaultActiveKey="1"
            items={[
              {
                key: "1  ",
                label: "工艺组成",
                children: (
                  <MesRoutingProcessPage
                    ref={processRef}
                    parentId={editingData?.id}
                  />
                ),
              },
              {
                key: "2  ",
                label: "关联产品",
                children: (
                  <MesRoutingProductPage
                    ref={productRef}
                    parentId={editingData?.id}
                  />
                ),
              },
            ]}
          />
        </Form>
      </Drawer>
    </Spin>
  );
}
